import { AppDataSource } from '../../config/database';
import { User, UserStatus } from '../../entities/User';
import bcrypt from 'bcryptjs';
import jwt from 'jsonwebtoken';
import { JWT_SECRET } from '../../middleware/auth';
import { UserInfo } from '../../types/auth';
import authConfig from '../../config/auth';
import logger from '../../utils/logger';

export class UserService {
  private userRepository = AppDataSource.getRepository(User);

  // 用户登录
  async login(mobile: string, password: string): Promise<User | null> {
    const user = await this.userRepository.findOne({ where: { mobile } });
    if (!user) return null;
    logger.info('user', user);
    
    // 假设密码存储在remarks字段中，实际应该创建专门的password字段
    const hashedPassword = user.remarks || '';
    const isValid = await bcrypt.compare(password, hashedPassword);
    if (!isValid) return null;

    return user;
  }

  // 更新登录信息
  async updateLoginInfo(userId: string, ip: string): Promise<void> {
    await this.userRepository.update(userId, {
      updateTime: new Date(),
      remarks: `上次登录IP: ${ip}` // 使用remarks字段存储登录信息
    });
  }

  // 修改密码
  async changePassword(userId: string, oldPassword: string, newPassword: string): Promise<boolean> {
    const user = await this.userRepository.findOne({ where: { id: userId } });
    if (!user) return false;

    // 假设密码存储在remarks字段中
    const hashedPassword = user.remarks || '';
    const isValid = await bcrypt.compare(oldPassword, hashedPassword);
    if (!isValid) return false;

    const newHashedPassword = await bcrypt.hash(newPassword, authConfig.SALT_STR);
    await this.userRepository.update(userId, { remarks: newHashedPassword });
    return true;
  }

  // 创建用户
  async createUser(userData: Partial<User>): Promise<User> {
    // 如果需要存储密码，使用remarks字段
    if (userData.remarks) {
      userData.remarks = await bcrypt.hash(userData.remarks, authConfig.SALT_STR);
    }
    const user = new User(userData);
    return await this.userRepository.save(user);
  }

  // 更新用户信息
  async updateUser(userId: string, userData: Partial<User>): Promise<boolean> {
    const result = await this.userRepository.update(userId, userData);
    return result.affected ? result.affected > 0 : false;
  }

  // 获取用户信息
  async getUserById(userId: string): Promise<User | null> {
    return await this.userRepository.findOne({ where: { id: userId } });
  }

  // 获取用户列表
  async getUsers(options: {
    skip?: number;
    take?: number;
    search?: string;
    status?: number;
  }): Promise<[User[], number]> {
    const queryBuilder = this.userRepository
      .createQueryBuilder('user')
      .skip(options.skip || 0)
      .take(options.take || 10);

    if (options.search) {
      queryBuilder.where(
        '(user.name LIKE :search OR user.nickname LIKE :search OR user.mobile LIKE :search)',
        { search: `%${options.search}%` }
      );
    }

    if (typeof options.status === 'number') {
      queryBuilder.andWhere('user.status = :status', { status: options.status });
    }

    return await queryBuilder.getManyAndCount();
  }

  // 生成用户Token
  generateToken(user: User): string {
    return jwt.sign(
      {
        id: user.id,
        name: user.name,
        nickname: user.nickname,
        mobile: user.mobile
      },
      JWT_SECRET,
      { expiresIn: '24h' }
    );
  }

  // 转换为UserInfo
  toUserInfo(user: User): UserInfo {
    return {
      id: Number(user.id.replace('TN_', '')), // 转换ID格式
      username: user.mobile, // 使用手机号作为username
      nickname: user.nickname || '',
      avatar: user.avatar || '',
      orgId: undefined, // User实体中没有orgId字段
      token: this.generateToken(user),
      orgName: ''
    };
  }

  // 验证手机号是否存在
  async isMobileExists(mobile: string): Promise<boolean> {
    const user = await this.userRepository.findOne({ where: { mobile } });
    return !!user;
  }

  // 禁用用户
  async disableUser(userId: string): Promise<boolean> {
    const result = await this.userRepository.update(userId, { status: UserStatus.DISABLED });
    return result.affected ? result.affected > 0 : false;
  }

  // 启用用户
  async enableUser(userId: string): Promise<boolean> {
    const result = await this.userRepository.update(userId, { status: UserStatus.NORMAL });
    return result.affected ? result.affected > 0 : false;
  }

  // 删除用户
  async deleteUser(userId: string): Promise<boolean> {
    // 使用软删除方式，将状态设为禁用
    const result = await this.userRepository.update(userId, { status: UserStatus.DISABLED });
    return result.affected ? result.affected > 0 : false;
  }
}